/*
 * =============================================================
 *
 *        Project:  apue
 *
 *       Filename:  f3_10.c
 *
 *         Editor:  vim :set et ts=2 sts=2 sw=2
 *
 *         Author:  Martin Y. Yang , yang@libpix.org
 *
 *    Description:  
 *
 * =============================================================
 */
/**
 * @file
 * @brief Figure 3.10 Print file flags for specified descriptor
 */

#include "apue.h"
#include <fcntl.h>

int fileflags_main(int argc, char *argv[])
{
  int val;

  if(argc != 2)
    err_quit("usage: apue 3.10 <descriptor#>");

  if((val = fcntl(atoi(argv[1]), F_GETFL, 0)) < 0)
    err_sys("fcntl error for fd %d", atoi(argv[1]));

  switch (val & O_ACCMODE) {
    case O_RDONLY:
      printf("read only");
      break;
    case O_WRONLY:
      printf("write only");
      break;
    case O_RDWR:
      printf("read write");
    default:
      err_dump("unknown access mode");
  }

  if (val & O_APPEND)
    printf(", append");
  if (val & O_NONBLOCK)
    printf(", nonblocking");
#if defined(O_SYNC)
  if (val & O_SYNC)
    printf(", synchronous writes");
#endif
#if !defined(_POSIX_C_SOURCE) && defined(O_FSYNC)
  if (val & O_FSYNC)
    printf(", synchronous writes");
#endif
  putchar('\n');
  exit(0);
}

